package com.qingyun.user.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;

import com.qingyun.model.common.dtos.R;
import com.qingyun.model.common.enums.AppHttpCodeEnum;
import com.qingyun.model.user.dtos.*;
import com.qingyun.model.user.pojos.User;
import com.qingyun.user.controller.KaptchaController;
import com.qingyun.user.mapper.UserMapper;
import com.qingyun.user.service.UserFanService;
import com.qingyun.user.service.UserFollowService;
import com.qingyun.user.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import utils.common.MD5Utils;
import utils.common.RegexUtils;
import utils.thread.AppThreadLocalUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static utils.common.RedisConstants.*;
import static utils.common.SystemConstants.USER_NICK_NAME_PREFIX;


@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserFanService userFanService;

    @Resource
    private UserFollowService userFollowService;


    @Override
    public R loginByPassword(LoginFormByPasswordDTO loginForm) {
        User user = query().eq("phone", loginForm.getPhone()).one();
        HttpSession session = KaptchaController.session;
        if (session==null){
            return R.error("验证码已失效！");
        }
        String captcha = (String) session.getAttribute("captcha");

        if (!captcha.equals(loginForm.getCode())){
            return R.error("验证码错误，请重新输入!");
        }
        if (user==null){
            return R.error("用户未注册！");
        }
        String salt = user.getSalt();
        String pswd = loginForm.getPassword();
        pswd = DigestUtils.md5DigestAsHex((pswd + salt).getBytes());
        if (!pswd.equals(user.getPassword())) {
            return R.error("密码错误");
        }
        String token = UUID.randomUUID().toString(true);

        LoginDto loginDto = BeanUtil.copyProperties(user, LoginDto.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(loginDto,new HashMap<>(),
                CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName,fieldValue)->fieldValue+""));
        String tokenKey = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
        stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL,TimeUnit.MINUTES);

        return R.success(token);

    }

    @Override
    public R<User> info(Long id) {
        User user = getById(id);
        user.setSalt("");
        user.setPassword("");
        Integer follow = userFollowService.query().eq("user_id", user.getId()).count();
        user.setFollowCount(follow);
        Integer fans = userFollowService.query().eq("follow_id", user.getId()).count();
        user.setFansCount(fans);
        isfollow(user);
        return R.success(user);
    }

    @Override
    public R reg(RegDto dto) {
        User one = query().eq("phone", dto.getPhone()).one();
        if (one!=null){
            return R.error("该手机号尚未注册");
        }
        if (dto.getPassword().isEmpty()){
            return R.error("密码不能为空");
        }
        if (RegexUtils.isPasswordInvalid(dto.getPassword())){
            return R.error("密码不合法");
        }

        HttpSession session = KaptchaController.session;
        if (session==null){
            return R.error("验证码已失效！");
        }
        String captcha = (String) session.getAttribute("captcha");
        if (!captcha.equals(dto.getPhoneCode())){
            return R.error("验证码错误");
        }

        User u=new User();
        u.setName(StringUtils.isBlank(dto.getName())?USER_NICK_NAME_PREFIX+RandomUtil.randomString(10):dto.getName());
        u.setImage(StringUtils.isBlank(dto.getImage())?"http://s3hieczd6.hn-bkt.clouddn.com/ai.jpg":dto.getImage());
        String slat = RandomUtil.randomNumbers(new Random().nextInt(10)+5);
        u.setSalt(slat);
        u.setPassword(MD5Utils.encodeWithSalt(dto.getPassword(),slat));
        u.setSex(dto.getSex());
        u.setPhone(dto.getPhone());
        boolean save = save(u);
        if (save){
            return R.success("注册成功");

        }
        return R.error("注册失败");
    }




    public void isfollow(User user) {
        User me = AppThreadLocalUtil.getUser();
        if (ObjectUtil.isNull(me)){
            return;
        }
        Long userId = me.getId();
        //判断当前用户是否关注
        Integer count = userFollowService.query().eq("user_id", userId).eq("follow_id", user.getId()).count();


        if (count>0) {
            //1为关注0为未关注
            user.setIsfollow(0);
        }else {
            user.setIsfollow(1);
        }

    }
}